#include<Arduino.h>

#include "parseCMD.hpp"

#include "../Global/globalDefs.hpp"
#include "../Global/globalVars.hpp"
#include "../tempUpdate/tempUpdate.hpp"
// is visualmicro, reference relative to project root
#include "../tPumpShared/COMM/comm.hpp"
#include "../tPumpShared/Misc/misc.hpp"
#include "../fanDriver/fanDriver.hpp"

//#include "comm.hpp"
//#include "misc.hpp"


#define DIRECT_OUTPUT print2Serial
#define COMM_OUTPUT Comm::sendStr

bool parseCMD(char* buffer, bool fromTrans) {
	if (StartWith(buffer, "add")) {
		buffer += sizeof("add");
		uint8_t newMac[6];
		for (int idx = 0; idx < 6; idx++) {
			newMac[idx] = strtol(buffer, &buffer, HEX);
			buffer++;
		}
		sprintf(Global::outputBuffer, "Parsed peer mac:%02X,%02X,%02X,%02X,%02X,%02X\r\n", newMac[0], newMac[1], newMac[2], newMac[3], newMac[4], newMac[5]);
		if (fromTrans) {
			COMM_OUTPUT(Global::outputBuffer);
		}
		else {
			DIRECT_OUTPUT(Global::outputBuffer);
		}
		Comm::addPeer(newMac, true);
		return true;
	}
	else if (StartWith(buffer, "who")) {
		if (fromTrans) {
			COMM_OUTPUT(who);
		}
		else {
			DIRECT_OUTPUT(who);
		}
		return true;
	}
	else if (StartWith(buffer, "which")) {
		if (fromTrans) {
			COMM_OUTPUT(which);
		}
		else {
			DIRECT_OUTPUT(which);
		}
		return true;
	}
	else if (StartWith(buffer, "version")) {
		if (fromTrans) {
			COMM_OUTPUT(version);
		}
		else {
			DIRECT_OUTPUT(version);
		}
		return true;
	}
	else if (StartWith(buffer, "config")) {
		buffer += sizeof("config");
		if (StartWith(buffer, "startup")) {
			buffer += sizeof("startup");
			int mode = atoi(buffer);
			Comm::setStartupMode(mode);
			return true;
		}
		else if (StartWith(buffer, "fan")) {
			buffer += sizeof("fan");
			int speed = atoi(buffer);
			Global::fanOutput = FanDriver::set(speed);
			return true;
		}
	}
	else if (StartWith(buffer, "?")) {
#define REPORT_FORMAT "TempFan@{%03d},TempTank@{%03d},FanDr@{%03d}%%\r\n"
		sprintf(Global::outputBuffer, REPORT_FORMAT, (int)Global::fanTemp, (int)Global::tankTemp, Global::fanOutput);
		if (fromTrans) {
			COMM_OUTPUT(Global::outputBuffer);
		}
		else {
			DIRECT_OUTPUT(Global::outputBuffer);
		}
		return true;
	}
	return false;
}
